package com.huanhong.hik.bean;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author zhls1
 */
@Data
@NoArgsConstructor
public class Result<T> {

    public static final String SUCCESSFUL_CODE = "200000";
    public static final String SUCCESSFUL_MSG = "处理成功";

    /**
     * 处理结果code
     */
    private String code;
    /**
     * 执行的方法
     */
    private String method;
    /**
     * 处理结果描述信息
     */
    private String msg;
    /**
     * 请求结果生成时间戳
     */
    private long timestamp;
    /**
     * 处理结果数据信息
     */
    private T data;


    public Result(String code, String msg) {
        this.code = code;
        this.msg = msg;
        this.timestamp = System.currentTimeMillis();
    }


    /**
     * 内部使用，用于构造成功的结果
     *
     * @param code
     * @param msg
     * @param data
     */
    private Result(String code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.timestamp = System.currentTimeMillis();
    }

    /**
     * 根据状态返回结果数据
     *
     * @param success
     * @return
     */
    public static Result render(boolean success) {
        if (success) {
            return success();
        } else {
            return fail();
        }
    }

    /**
     * 快速创建成功结果并返回结果数据
     *
     * @param data
     * @return Result
     */
    public static Result success(Object data) {
        return new Result<>(SUCCESSFUL_CODE, SUCCESSFUL_MSG, data);
    }

    /**
     * 快速创建成功结果
     *
     * @return Result
     */
    public static Result success() {
        return success(null);
    }

    public static Result fail() {
        return new Result<>("500", "系统异常", null);
    }


    /**
     * @param code
     * @param throwable
     * @return
     */
    public static Result fail(String code, Throwable throwable) {
        return fail(code, throwable.getClass().getName() + ", " + throwable.getMessage());
    }

    public static Result fail(String code, String msg) {
        return new Result(code, msg);
    }

    /**
     * 成功code=000000
     *
     * @return true/false
     */
    public boolean isSuccess() {
        return SUCCESSFUL_CODE.equals(this.code);
    }

    /**
     * 失败
     *
     * @return true/false
     */
    @JSONField(serialize = false)
    public boolean isFail() {
        return !isSuccess();
    }

    public String toJsonString() {
        return JSON.toJSONString(this);
    }
}
